package server;

import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class ClientHandler extends Thread {
    /*
    this is a protocol including the format about the communication with server and client
    it set the server action for different command from clients
     */

    private Socket socket;

    public ClientHandler(Socket socket) {
        /*
        init a socket
         */
        super("ClientHandler");
        this.socket = socket;
    }

    public void run() {
        /*
        Multithreading method
        do some action for command
         */
        try {
            // Get the address of the client. Also get the date. This information could be
            // added to a log file, for instance.
            InetAddress inet = socket.getInetAddress();

            // Get work path
            String curPath = System.getProperty("user.dir");

            // Get the point of this file,
            // if there is no file, create it
            File log = new File(curPath + "log.txt");
            if(!log.exists()){
                log.createNewFile();
            }
            // file writer and reader
            FileWriter fileWritter = new FileWriter(log,true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);


            // pipe connected with client to write and read
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true );

            // message from client
            String[] command = reader.readLine().split(" ");
            String msg = command[0];

            if (command.length==1&&msg.compareTo("list")==0){
                // current path
                String path = System.getProperty("user.dir");
                // get all filenames
                List<String> fileList = getFiles(path + File.separatorChar + "serverFiles");
                for(String file:fileList){
                    String filename = file.substring(file.lastIndexOf(File.separatorChar)+1);
                    writer.println(filename);
                }
            }
            else{
                msg = command[1];
                String filename = null;
                String path = System.getProperty("user.dir");
                List<String> fileList = getFiles(path +  File.separatorChar + "serverFiles");
                for(String file:fileList){
                    if (file.substring(file.lastIndexOf(File.separatorChar)+1).compareTo(msg)==0){
                        filename = file;
                        break;
                    }
                }
                if (filename==null){
                    writer.println("No this file");
                }
                else{
                    writer.println("find it");
                    File file = new File(filename);
                    //read file
                    FileInputStream fis = new FileInputStream(file);
                    //print file into stream
                    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

                    //filename and length
                    dos.writeUTF(file.getName());
                    dos.flush();
                    dos.writeLong(file.length());
                    dos.flush();

                    byte[] bytes = new byte[1024];
                    int length;
                    //use loop to store file into bytes then send it by dos
                    while((length = fis.read(bytes, 0, bytes.length)) != -1) {
                        dos.write(bytes, 0, length);
                        dos.flush();
                    }
                    fis.close();
                    dos.close();
                }
                msg = "get " + msg;
            }
            Date date = new Date();
            SimpleDateFormat formatDate = new SimpleDateFormat("YYYY/MM/dd : HH:mm:ss ");
            String logText = formatDate.format(date) + ": " + inet.toString() + " : " + msg;
            System.out.println(logText);
            bufferWritter.write(logText+"\n");
            bufferWritter.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public List<String> getFiles(String path) {
        /*
        get a specialised file from server
         */
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
            }
        }
        return files;
    }
}
